
#import "RNUpush.h"
#import "UMPushHelper.h"
@interface RNUpush()
@property (nonatomic, strong) dispatch_source_t timer;

@end
  
@implementation RNUpush


RCT_EXPORT_MODULE(RNUpushModule)

- (dispatch_queue_t)methodQueue
{
    return dispatch_get_main_queue();
}

RCT_EXPORT_METHOD(init:(RCTPromiseResolveBlock)resolve
                  reject:(RCTPromiseRejectBlock)reject){
    
    //定时器开始执行的延时时间
    NSTimeInterval delayTime = 1.0f;
    //定时器间隔时间
    NSTimeInterval timeInterval = 1.0f;
    //创建子线程队列
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    //使用之前创建的队列来创建计时器
    _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);

    //设置延时执行时间，delayTime为要延时的秒数
    dispatch_time_t startDelayTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayTime * NSEC_PER_SEC));
    //设置计时器
    dispatch_source_set_timer(_timer, startDelayTime, timeInterval * NSEC_PER_SEC, 0.1 * NSEC_PER_SEC);

    
    __weak typeof(self) weakSelf = self;
    __block int count = 0;
    dispatch_source_set_event_handler(_timer, ^{
        //执行事件
        NSString * deviceToken = [UMPushHelper share].devicetoken;
        if(deviceToken != nil && deviceToken.length>0){
            resolve(deviceToken);
            dispatch_source_cancel(weakSelf.timer);
        }else if(count > 3){
            resolve('0000000-0000000-0000000-0000000');
            dispatch_source_cancel(weakSelf.timer);
        } 
        count ++;
    });
    // 启动计时器
    dispatch_resume(_timer);

}



- (void)startObserving{
  [[NSNotificationCenter defaultCenter] addObserver:self
                                           selector:@selector(emitEventInternal:)
                                               name:@"UMPushNotificationEvent"
                                             object:nil];
}
- (void)stopObserving{
  [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)emitEventInternal:(NSNotification *)notification{
  [self sendEventWithName:@"UMPushNotificationEvent"
                     body:notification.userInfo];
}

+(void)emitEventPayload:(NSDictionary *)payload{
  [[NSNotificationCenter defaultCenter] postNotificationName:@"UMPushNotificationEvent"
                                                      object:self
                                                    userInfo:payload];
}

- (NSArray<NSString *> *)supportedEvents
{
  return @[@"UMPushNotificationEvent"];
}
@end
  
